class QuestionStore {
  constructor(id) {
    this._id = id
  }

  _cache = []
  _subscriber = {}
  _topicCache = {}
  currentIndex = 0

  setQuestions(list) {
    this._cache = JSON.parse(JSON.stringify(list))
  }

  initList(index, list) {
    this.setQuestions(list)
    this.publish('initList', {index, list})
    this.changeIndex(index)
  }

  setQuestion(index, question) {
    this._cache[index].question = JSON.parse(JSON.stringify(question))
    this.publish('refreshQuestion', {index, question: JSON.parse(JSON.stringify(question))})
  }

  getQuestion(index) {
    if (this._cache[index].question) {
      return JSON.parse(JSON.stringify(this._cache[index].question))
    }
    return null
  }

  getItem(index) {
    if (this._cache[index]) {
      const item = JSON.parse(JSON.stringify(this._cache[index]))
      delete item.question
      return item
    }
    return null
  }

  getCurrentItem() {
    return this.getItem(this.currentIndex)
  }

  getCurrentQuestion() {
    return this.getQuestion(this.currentIndex)
  }

  changeIndex(currentIndex) {
    this.currentIndex = currentIndex
    this.publish('changeIndex', currentIndex)
  }

  answer({index, status, result}) {
    this._cache[index].status = status
    this._cache[index].result = result
    // console.log('answer', this._cache[index])
    this.publish('answer', {index, status, result, question: this._cache[index].question})
  }

  clearAnswer() {
    this._cache.map(item => {
      delete item.status
      delete item.result
      if (item.question) {
        delete item.question.status
        item.question.result = []
      }
    })

    console.log('clearAnswer, finished')
  }

  getAnswer(index) {
    return this._cache[index]
  }

  destroy() {
    this._cache = []
    this._subscriber = {}
    this._topicCache = {}
  }

  publish(topic, data) {
    this._topicCache[topic] = data
    const arr = this._subscriber[topic] || []
    for (let i = 0; i < arr.length; i++) {
      try {
        arr[i](data)
      } catch (e) {
        console.log(topic, data, e)
      }
    }
  }

  subscribe(topic, cb) {
    if (!this._subscriber[topic]) {
      this._subscriber[topic] = []
    }

    this._subscriber[topic].push(cb)

    if (this._topicCache[topic]) {
      // console.log('cached', topic)
      cb(this._topicCache[topic])
    }
  }
}


global.q = {
  map: {},
  createStore() {
    const id = Date.now()
    this.map[id] = new QuestionStore(id)
    return id
  },
  getStore(id) {
    return this.map[id]
  },
  destroyStore(id) {
    if (this.map[id]) {
      this.map[id].destroy()
      delete this.map[id]
    }
  }
}
export default q
